package com.moyun.search.dao.repository;

import com.moyun.search.common.config.ElasticSearchConfig;
import com.moyun.search.domain.FileLab;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.DocumentResult;
import io.searchbox.core.Index;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;

/**
 * 项目文件库存储
 * @author: zealon
 * @since: 2021/12/22
 */
@Slf4j
@Repository
public class ProjectFileLabRepository {

    @Autowired
    private JestClient jestClient;
    @Autowired
    private ElasticSearchConfig elasticSearchConfig;

    /**
     * 保存 Document
     * @param fileLab
     * @return
     */
    public JestResult saveDocument(FileLab fileLab) {
        DocumentResult result = null;
        Index index = new Index.Builder(fileLab)
                .index(elasticSearchConfig.getIndexName())
                .type(elasticSearchConfig.getType())
                .id(fileLab.getId().toString())
                .setParameter("pipeline","attachment")
                .refresh(true)
                .build();
        try {
            result = jestClient.execute(index);
            log.info("{}存储到ES库，result={}", fileLab.getFile_name(), result);
        } catch (IOException e) {
            log.warn("存储到ES库异常!data={}", fileLab.getFile_name(), e.getMessage());
        }
        return result;
    }
}
